package com.gym.controller.user;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.gym.VO.ResultVO;
import com.gym.converter.CreateUserForm2UserBaseInfoDTOConverter;
import com.gym.converter.CreateUserForm2UserDetailInfoConverter;
import com.gym.converter.UpdateDetailForm2UserDetailInfo;
import com.gym.dto.user.UserBaseInfoDTO;
import com.gym.enums.ResultEnum;
import com.gym.form.user.CreateUserForm;
import com.gym.form.user.UpdateDetailForm;
import com.gym.form.user.UpdatePasswordForm;
import com.gym.pojo.user.Role;
import com.gym.pojo.user.UserBaseInfo;
import com.gym.pojo.user.UserDetailInfo;
import com.gym.pojo.user.UserRole;
import com.gym.service.user.RoleService;
import com.gym.service.user.UserRoleService;
import com.gym.service.user.UserService;
import com.gym.utils.ResultVOUtil;
import com.gym.utils.UserValidate;

@Controller
@RequestMapping(value = "user")
public class UserController {

	@Autowired
	private UserService userService;

	@Autowired
	private RoleService roleService;

	@Autowired
	UserRoleService userRoleService;

	/**
	 * 添加用户
	 * @param createUserForm
	 * @return
	 */
	// @RequiresAuthentication
	@RequiresPermissions("user:add")
	@RequestMapping(value = "create", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
	@ResponseBody
	public ResultVO newUser(@RequestBody CreateUserForm createUserForm) {

		// if (ShiroFilterUtils.isAjax(request)) {// ajax请求
		// Map<String, String> resultMap = new HashMap<String, String>();
		// LoggerUtils.debug(getClass(), "当前用户没有登录，并且是Ajax请求！");
		// resultMap.put("login_status", "300");
		// resultMap.put("message",
		// "\u5F53\u524D\u7528\u6237\u6CA1\u6709\u767B\u5F55\uFF01");//
		// 当前用户没有登录！
		// ShiroFilterUtils.out(response, resultMap);
		// }

		UserBaseInfoDTO userBaseInfoDTO = CreateUserForm2UserBaseInfoDTOConverter
				.convert(createUserForm);
		// 添加用户基本信息
		ResultVO addBaseInfoResult = userService
				.addUserBaseInfo(userBaseInfoDTO);

		// 添加用户基本信息失败
		if (addBaseInfoResult.getCode() != 0) {
			return addBaseInfoResult;
		}

		/**
		 *  添加用户详细信息
		 */
		UserDetailInfo userDetailInfo = CreateUserForm2UserDetailInfoConverter
				.convert(createUserForm);

		// 获得用户信息
		UserBaseInfo userBaseInfo = (UserBaseInfo) addBaseInfoResult.getData();

		// 设置用户编号
		userDetailInfo.setUserId(userBaseInfo.getUserId());

		// 添加用户详细信息
		ResultEnum addDetailInfoResult = userService
				.addUserDetailInfo(userDetailInfo);

		// 添加用户详细信息失败
		if (addDetailInfoResult.getCode() != 0) {
			this.userService.deleteUserBaseInfo(userBaseInfo.getUserId());
			return ResultVOUtil.error(addDetailInfoResult);
		}

		/**
		 *  为用户添加角色
		 */
		// 通过角色名获得用户角色
		Role role = roleService.getByName(createUserForm.getRoleName());
		UserRole userRole = new UserRole();
		userRole.setUserId(userBaseInfo.getUserId());
		userRole.setRoleId(role.getRoleId());
		// 为用户分配角色
		this.userRoleService.addUserRole(userRole);

		return ResultVOUtil.success();
	}

	/**
	 * 根据用户编号删除单个用户
	 * @param userId
	 * @return
	 */
	@RequestMapping(value = "{userId}/del", method = RequestMethod.DELETE, produces = "application/json;charset=UTF-8")
	@ResponseBody
	public ResultVO deleteUserById(@PathVariable(value = "userId") Long userId) {

		// 删除用户基本信息
		ResultEnum deleteBaseResult = userService.deleteUserBaseInfo(userId);

		// 删除用户详细信息
		ResultEnum deleteDetailResult = userService
				.deleteUserDetailInfo(userId);

		// 删除用户关联的角色
		ResultEnum deleteUserRoleResult = userRoleService
				.deleteUserRole(userId);

		if (deleteBaseResult.getCode() != 0) {
			return ResultVOUtil.error(deleteBaseResult);
		}

		if (deleteDetailResult.getCode() != 0) {
			return ResultVOUtil.error(deleteDetailResult);
		}

		if (deleteUserRoleResult.getCode() != 0) {
			return ResultVOUtil.error(deleteUserRoleResult);
		}

		return ResultVOUtil.success();
	}

	/**
	 * 根据传入的多个用户编号删除多个用户
	 * @param ids
	 * @return
	 */
	@RequestMapping(value = "{ids}/delmore", method = RequestMethod.DELETE, produces = "application/json;charset=UTF-8")
	@ResponseBody
	public ResultVO deleteUsersByIds(@PathVariable(value = "ids") String ids) {
		String[] userIds = ids.split(",");
		for (int i = 0; i < userIds.length; i++) {
			ResultVO result = deleteUserById(Long.parseLong(userIds[i]));
			if (result.getCode() != 0) {
				return result;
			}
		}
		return ResultVOUtil.success();
	}

	/**
	 * 修改用户密码
	 * @param updatePasswordForm
	 * @return
	 */
	@RequestMapping(value = "password/update", method = RequestMethod.PUT, produces = "application/json;charset=UTF-8")
	@ResponseBody
	public ResultVO updatePassword(
			@RequestBody UpdatePasswordForm updatePasswordForm) {

		// 修改用户密码
		ResultEnum updateResult = this.userService
				.updatePassword(updatePasswordForm);

		if (updateResult.getCode() != 0) {
			return ResultVOUtil.error(updateResult);
		}

		return ResultVOUtil.success();
	}

	/**
	 * 修改用户详细信息
	 * @param userDetailInfo
	 * @return
	 */
	@RequiresPermissions("user:add")
	@RequestMapping(value = "detail/update", method = RequestMethod.PUT, produces = "application/json;charset=UTF-8")
	@ResponseBody
	public ResultVO updateDetailInfo(
			@RequestBody UpdateDetailForm updateDetailForm) {

		UserDetailInfo userDetailInfo = UpdateDetailForm2UserDetailInfo
				.convert(updateDetailForm);

		ResultEnum resultEnum = this.userService
				.updateUserDetailInfo(userDetailInfo);
		if (resultEnum.getCode() != 0) {
			return ResultVOUtil.error(resultEnum);
		}
		return ResultVOUtil.success();
	}

	/**
	 * 根据手机号码返回用户基本信息
	 * @param phoneNumber
	 * @return
	 */
	@RequestMapping(value = "phoneNum/user/get", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
	@ResponseBody
	public ResultVO getUserBaseInfo(@RequestParam String phoneNumber) {

		// 手机号码判空
		if (UserValidate.isNull(phoneNumber)) {
			return ResultVOUtil.error(ResultEnum.USER_TEL_IS_NULL);
		}

		// 手机号码格式不正确
		if (!UserValidate.isHandset(phoneNumber)) {
			return ResultVOUtil.error(ResultEnum.TEL_FORMAT_ERROR);
		}

		UserDetailInfo userDetailInfo = this.userService
				.getUserDetailInfoByPhoneNumber(phoneNumber);

		if (userDetailInfo == null) {
			return ResultVOUtil.error(ResultEnum.NOT_EXIST_USER);
		}

		UserBaseInfo userBaseInfo = this.userService
				.getUserBaseInfoById(userDetailInfo.getUserId());

		return ResultVOUtil.success(userBaseInfo);

	}

	// @RequiresPermissions("user:add")
	@RequestMapping(value = "page", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
	@ResponseBody
	public ResultVO PageInfo(@RequestParam(defaultValue = "1") int currentPage,
			@RequestParam(defaultValue = "5") int pageSize) {
		return ResultVOUtil.success(this.userService.pageInfos(currentPage,
				pageSize));
	}
}
